<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div class="structure_main">
    <div class="left">
      <div class="title">机型部段结构定义</div>
      <el-tree default-expand-all :data="treeData" @node-contextmenu="openMenu" ref="tree" node-key="id" :props="defaultProps">
        <template #default="{ node,data }">
          <span class="custom-tree-node">
            <span class="node-title" v-if="node.level === 3">{{ data.mark }}({{ node.label }}) </span>
            <span class="node-title" v-else>{{ node.label }} </span>
          </span>
        </template>
      </el-tree>

      <!-- 自定义右键菜单 -->
      <div v-show="menuVisible" :style="menuStyle" class="custom-menu" ref="wrapper">
        <ul>
          <li @click="handleMenuClick('add')">
            <el-button size="small" link type="primary" icon="Plus" :class="{'disable':menuLevel === 4}" :disabled="menuLevel === 4">添加</el-button>
          </li>
          <li @click="handleMenuClick('edit')">
            <el-button size="small" link type="primary" icon="Edit" :class="{'disable':menuLevel === 1}" :disabled="menuLevel === 1">编辑</el-button>
          </li>
          <li @click="handleMenuClick('delete')">
            <el-button size="small" link type="primary" icon="Delete" :class="{'disable':menuLevel === 1}" :disabled="menuLevel === 1">删除</el-button>
          </li>
        </ul>
      </div>
    </div>
    <div class="right" v-if="showAdd">
      <el-form size="small" label-width="220" ref="formRef" :model="formData" :rules="rules">
        <el-form-item label="节点标识：" required prop="mark">
          <el-input v-model="formData.mark" :disabled="editFlag" />
        </el-form-item>
        <el-form-item :label="generateNodeName()" required prop="name">
          <el-select v-if="menuLevel === 2 && !editFlag || menuLevel == 3" v-model="formData.name" placeholder="请选择">
            <el-option v-for="(item, index) in sectionDicts" :key="sectionDicts[index]" :label="sectionDicts[index]" :value="sectionDicts[index]"></el-option>
          </el-select>
          <el-input v-else v-model="formData.name" />
        </el-form-item>
        <!-- <el-form-item v-if="(menuLevel === 2 && !editFlag) || (menuLevel === 3 && editFlag)" label="是否为模型组建时所用批次：" prop="taskDefault">
          <el-radio-group v-model="formData.taskDefault">
            <el-radio :value="1" size="small">是</el-radio>
            <el-radio :value="2" size="small">否</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" @click="submitMenu">保存</el-button>
          <el-button @click="cancelMenu">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>

</template>
<script  setup name="Structure">
import { getDicts } from '@/api/system/dict/data';
import { getStructureTree, addStructureMenu, updateStructureMenu, deleteStructureMenu } from '@/api/dataAcquisition';
const treeData = ref([]);
const defaultProps = {
  children: 'children',
  label: 'label'
};
const sectionDicts = ref([]);
const menuVisible = ref(false);
const mentRemoveCheck = ref(false);
const menuStyle = ref({
  left: 0,
  top: 0
});
const formRef = ref(null);
// const rules = {
//   name: [{ required: true, message: '节点名称不能为空', trigger: 'blur' }],
//   mark: [{ required: true, message: '节点标识不能为空', trigger: 'blur' }]
// };

const rules = computed(() => { 
  let ruleMsg = '';
  switch (menuLevel.value) {   
    case 1:
      ruleMsg = editFlag.value ? '节点名称不能为空' : '机型型号不能为空';
      break;
    case 2:
      ruleMsg = editFlag.value ? '机型型号不能为空' : '部段名称不能为空';
      break;
    case 3:
      ruleMsg = editFlag.value ? '部段名称不能为空' : '子部段名称不能为空';
      break;
    default:    // 其他情况
      ruleMsg = '节点名称不能为空';
  }
  return {
    name: [{ required: true, message: ruleMsg, trigger: 'blur' }],
    mark: [{ required: true, message: '节点标识不能为空', trigger: 'blur' }]
  }
});
const wrapper = ref(null);
const showAdd = ref(false);
const formData = ref({ name: '', mark: '', taskDefault: '' });
const nodeContent = ref(null);
const editFlag = ref(false);
const menuLevel = ref(null);
const generateNodeName = () => {
  switch (menuLevel.value) {    // 根据节点等级生成节点名称
    case 1:
      return '机型型号：';
    case 2:
      return editFlag.value ? '机型型号：' : '部段名称：';
    case 3:
      return editFlag.value ? '部段名称：' : '子部段名称：';
    default:    // 其他情况
      return '子部段名称：';
  }
}
const cancelMenu = () => {
  showAdd.value = false;
}
// 查询类型字典
getDicts('model_mesh').then((res) => {
  if (res.data) {
    sectionDicts.value = JSON.parse(res.data.find(item => item.dictLabel == 'section_name_config')?.dictValue);
  }
});
const handleMenuClick = (command) => {
  formData.value = {};
  if (command === 'add') {
    showAdd.value = true;
    editFlag.value = false;
    formData.value.name = '';
    formData.value.mark = '';
    formData.value.taskDefault = '';
  }
  if (command === 'edit') {
    showAdd.value = true;
    editFlag.value = true;
    formData.value.name = nodeContent.value.label;
    formData.value.mark = nodeContent.value.mark;
    formData.value.taskDefault = nodeContent.value.taskDefault;
  }
  formRef.value && formRef.value.clearValidate();
  if (command === 'delete') {
    showAdd.value = false;
    ElMessageBox.confirm('删除此目录后，该目录下的所有文件都将被永久删除且无法恢复，您是否确认执行此操作？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      deleteStructureMenu(nodeContent.value.id)
        .then((res) => {
          if (res) {
            ElMessage({ showClose: true, message: '删除成功。', type: 'success' });
            queryTreeMenu();
          }
        })
        .catch(() => {
          ElMessage({ showClose: true, message: '删除失败。', type: 'error' });
        });
    });
  }
  menuVisible.value = false;
};
// 右键点击
const openMenu = (event, data, node, element) => {
  menuLevel.value = node.level;
  nodeContent.value = data;
  // 显示菜单
  menuVisible.value = true;
  // 阻止默认的右键菜单显示
  event.preventDefault();
  // 设置菜单的位置
  menuStyle.value.left = 210 + 'px';
  menuStyle.value.top = event.clientY - 82 + 'px';
};
const handleClick = (event) => {
  // 检查点击是否发生在外部
  if (wrapper.value && !wrapper.value.contains(event.target)) {
    menuVisible.value = false;
  }
};
// 处理数节点数据
const processData = (data) => {
  const labelData = data.map((el) => {
    if (el.children) {
      el = { ...el, label: el.name };
      el.children = processData(el.children);
    } else {
      el = { ...el, label: el.name };
    }
    return el;
  });
  return labelData;
};
// 提交数据
const submitMenu = () => {
  formRef.value.validate((valid) => {
    console.log("校验结果")
    console.log(valid)
    if (!valid) {
      return false;
    }
    
    // 新增
    if (!editFlag.value) {
      formData.value.parentId = nodeContent.value.id;
      formData.value.level = menuLevel.value;
      if (!nodeContent.value.id) {
        formData.value.parentId = 0;
      }
      addStructureMenu(formData.value)
        .then((res) => {
          if (res) {
            ElMessage({ showClose: true, message: '新增成功。', type: 'success' });
            queryTreeMenu();
          }
        })
        .catch(() => {
          ElMessage({ showClose: true, message: '新增失败。', type: 'error' });
        });
    } else {
      formData.value.level = menuLevel.value - 1;
      formData.value = { ...nodeContent.value, ...formData.value };
      delete formData.value.children;
      updateStructureMenu(formData.value)
        .then((res) => {
          if (res) {
            ElMessage({ showClose: true, message: '修改成功。', type: 'success' });
            queryTreeMenu();
          }
        })
        .catch(() => {
          ElMessage({ showClose: true, message: '修改失败。', type: 'error' });
        });
    }
  });
};
const queryTreeMenu = () => {
  getStructureTree().then(async (res) => {
    if (res?.data) {
      const dataArr = res?.data || [];
      const returnData = await processData(dataArr);
      const treeDataTmp = [{ label: '机型', name: '', parentId: null, mark: '', children: returnData, level: 0 }];
      treeData.value = treeDataTmp;
    }
  });
};
onMounted(() => {
  queryTreeMenu();
  window.addEventListener('click', handleClick);
});
onUnmounted(() => {
  window.removeEventListener('click', handleClick);
});
</script>
<style lang="less" scoped>
.structure_main {
  padding-top: 10px;
  font-size: 12px;
  display: flex;
  height: calc(100vh - 94px);
  overflow: auto;
  .left {
    width: 300px;
    position: relative;
    border-right: 1px solid #ebebeb;
    padding: 10px;
    padding-bottom: 20px;
    min-height: calc(100vh - 94px);
    .title {
      font-weight: 600;
    }
    .custom-menu {
      position: absolute;
      background-color: #fff;
      border: 1px solid #ebebeb;
      border-radius: 3px;
      width: 80px;
      z-index: 1000;
      font-size: 12px;
      ul {
        margin: 0;
        padding: 5px 0;
        list-style: none;
        font-size: 12px;
      }
      ul li {
        padding: 3px 15px;
        cursor: pointer;
        font-size: 12px;
        display: flex;
        align-items: center;
      }
      ul li:hover {
        background-color: #eee;
      }
    }
    :deep(.el-tree-node__label) {
      font-size: 12px;
    }
    .custom-tree-node{
      font-size: 12px;
    }
  }
  .right {
    padding: 10px 10px 10px 20px;
  }
  .disable{
    color:#d9d9d9;
  }
}
</style>